// API基础配置
const BASE_URL = 'http://localhost:8080/api' // 后端服务地址

// 统一请求方法
const request = (options) => {
  if (false) { // 完全禁用mock模式
    throw new Error('Mock data is disabled')
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.headers
      },
      success: (res) => {
        console.log('API请求详情:', {
          url: BASE_URL + options.url,
          method: options.method,
          params: options.data,
          response: res
        })
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          console.error('API请求失败:', {
            url: BASE_URL + options.url,
            status: res.statusCode,
            error: res.data
          })
          reject({
            code: res.statusCode,
            message: res.data?.message || `请求失败: ${res.statusCode}`,
            data: res.data
          })
        }
      },
      fail: (err) => {
        reject({
          code: -1,
          message: '网络错误，请检查连接'
        })
      }
    })
  })
}

// 文章相关API
const articleApi = {
  // 获取文章列表
  getArticleList(params) {
    return request({
      url: '/articles/latest', // 匹配后端API路径
      method: 'GET',
      data: {
        pageNum: params.page || 1,
        pageSize: params.size || 10,
        category: params.category
      }
    })
  },
  
  // 获取文章详情
  getArticleDetail(id) {
    return request({
      url: `/articles/${id}`, // 匹配后端API路径
      method: 'GET'
    })
  },
  
  // 获取所有分类
  getAllCategories() {
    return request({
      url: '/articles/categories', // 匹配后端API路径
      method: 'GET'
    })
  }
}

// 用户相关API
const userApi = {
  login(data) {
    return request({
      url: '/auth/login',
      method: 'POST',
      data
    })
  },
  
  getUserInfo() {
    return request({
      url: '/user/info',
      method: 'GET'
    })
  }
}

module.exports = {
  articleApi,
  userApi,
  request
}
